package com.coffee.oss.strategy.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.coffee.common.exception.CustomException;
import com.coffee.oss.strategy.FileStorageStrategy;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 抽象的文件存储
 *
 * @author Kevin
 */
public abstract class AbstractFileStorage implements FileStorageStrategy {

    /**
     * 默认大小 50M
     */
    private static long DEFAULT_FILE_MAX_SIZE = 50 * 1024 * 1024;

    @Override
    public void checkFile(MultipartFile file) {
        if (file.getSize() > DEFAULT_FILE_MAX_SIZE) {
            throw new CustomException(String.format("文件超过最大限制，最大%sM", DEFAULT_FILE_MAX_SIZE / 1024 / 1024));
        }
    }

    @Override
    public String getFilepath(MultipartFile file, String bizPath) throws IOException {
        String extName = FileUtil.extName(file.getOriginalFilename());
        if (StrUtil.isBlank(extName)) {
            extName = FileTypeUtil.getType(file.getInputStream());
        }
        String filename = IdUtil.fastSimpleUUID() + "." + extName;
        String filepath = "/" + bizPath + "/" + DateUtil.today() + "/" + filename;
        return filepath;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param bizPath
     * @return
     * @throws IOException
     */
    @Override
    public abstract String upload(MultipartFile file, String bizPath) throws IOException;

}
